<?php 
class ComAdController extends ObjectController
{
	public function editAd($fields = array(), $isValid=0)
	{
		global $katana;
		global $adc;

		if(($adc->getCurrentAdId() > 0) && (count($fields) > 0))
		{
			if(is_object($adc->getCurrentAd()))
			{
				$params = array();
				$params['IsValid'] = $isValid;
				foreach(array_keys($fields) as $key)
				{
					$objectVar = $fields[$key]->getName();
					if($adc->varExsists($objectVar, $adc->CurrentAd))
					{
						switch($objectVar)
						{
							case 'Title':
							case 'TitleEn':
							case 'Description':
							case 'DescriptionEn':
							case 'ProductLinkTxt':
							case 'ProductLinkTxt2':
							case 'PriceCurrency':
							case 'Model':
							case 'SerialNo':
							case 'ContactEmail':
							case 'ContactName':
							case 'ContactCompany':
							case 'ContactMob':
							case 'ContactPhone':
							case 'ContactWeb':
							case 'LocationAddress':
							case 'LocationZip':
							case 'LocationCity':
							case 'LocationCountry':
							//Ad Vehicle
							case 'RegistrationNo':
							case 'RegNo':
							case 'CabinType':
							case 'SuspensionFront':
							case 'SuspensionRear':
							case 'ShaftType':
							//Ad Vehicle End
							//Ad VehicleLight
							case 'ColorTxt':
							case 'GearTypeTxt':
							case 'WheelDriftTxt':
							//Ad VehicleLight End
							//Ad Transport
							case 'FromCountry':
							case 'FromCity':
							case 'FromZip':
							case 'ToCountry':
							case 'ToCity':
							case 'ToZip':
							//Ad Transport End
							//Ad Employement
							//Ad Employement End
								if(self::formatText($fields[$key]->getValue()) !== $adc->CurrentAd->__call('get'.$objectVar))
								{
									$params[$objectVar] = self::formatText($fields[$key]->getValue());
									$adc->CurrentAd->setDataChanged(true);
								}
							break;
							case 'ProductLink':
							case 'ProductLink2':
								if(self::formatRemoteUrl($fields[$key]->getValue()) !== self::formatRemoteUrl($adc->CurrentAd->__call('get'.$objectVar)))
								{
									$params[$objectVar] = self::formatRemoteUrl($fields[$key]->getValue());
									$adc->CurrentAd->setDataChanged(true);
								}
							break;
							case 'TypeId':
							case 'CatId':
							case 'BrandId':
							case 'ModId':
							case 'IsBuying':
							case 'IsNew':
							case 'PriceDisplay':
							case 'Year':
							case 'LengthUsed':
							case 'Weight':
							case 'Power':
							case 'Volume':
							//Ad Vehicle
							case 'AdVehicleId':
							case 'EuApproved':
							case 'MaintenanceDoc':
							case 'AirCondition':
							case 'AditionalHydra':
							case 'CeMarked':
							case 'ConformityDeclaration':
							case 'AutoTrans':
							case 'TrailerBreak':
							case 'LoadCapacityVolume':
							case 'LoadCapacityWeight':
							case 'Wheelbase':
							case 'TailLift':
							case 'InsideLength':
							case 'InsideWidth':
							case 'ClutchlessTurningGear':
							case 'SpeedGear':
							case 'SpringCottage':
							case 'SuspFrontAxle':
							case 'IsTracked':
							//Ad Vehicle End
							//Ad VehicleLight
							/* Main values */
							case 'ColorId':
							case 'CountSeats':
							case 'CountDoors':
							case 'FuelType':
							case 'GearType':
							case 'WheelDrift':
							case 'OwnersCount':
							case 'TaxClass':
							case 'TechApproved':
							/* Equipement */
							/* Safety values */
							case 'ABS':
							case 'AirbagFront':
							case 'AirbagSide':
							case 'Alarm':
							case 'DiffLock':
							case 'TractionControll':
							case 'AntiSlipRegulation':
							case 'EngineImmobilizer':
							case 'SteelBeams':
							case 'RemovableHitch':
							case 'DieselParticleFilter':
							/* Equipement */
							case 'AllSeasonTires':
							case 'Hitch':
							case 'CargoHolder':
							case 'LightAlloyWheelsSummer':
							case 'LightAlloyWheelsWinter':
							case 'AirSuspension':
							case 'MetallicPaint':
							case 'LevelControll':
							case 'ParkingSensorFront':
							case 'ParkingSensorRear':
							case 'WheelsSummer':
							case 'WheelsWinter':
							case 'RoofRails':
							case 'XenonHeadlight':
							/* Comfort */
							case 'AirCon':
							case 'BaggageCover':
							case 'CdChanger':
							case 'CruiseControl':
							case 'PartialLeather':
							case 'DVD':
							case 'PowerSeat':
							case 'PowerSeatMemory':
							case 'PowerMirrors':
							case 'PowerWindows':
							case 'TintedGlass':
							case 'Handsfree':
							case 'KeylessGo':
							case 'TripComputer':
							case 'CentreArmrest':
							case 'EngineHeater':
							case 'MultifunctionSteering':
							case 'GPS':
							case 'HeatedSeats':
							case 'RadioCD':
							case 'RainSensor':
							case 'CentralLock':
							case 'Servo':
							case 'LeatherInterior':
							case 'SportSeats':
							case 'Sunroof':
							case 'Tv':
							//Ad VehicleLight End
							//Ad Transport
							case 'Length':
							case 'Width':
							case 'StandingOrder':
							//Ad Transport
							//Ad Employement
							case 'IsFullTime':
							case 'EmploymentType':
							case 'CountryPart':
							case 'Diploma':
							//Ad Employement End
								if(intval($fields[$key]->getValue()) != $adc->CurrentAd->__call('get'.$objectVar))
								{
									$params[$objectVar] = intval($fields[$key]->getValue());
									$adc->CurrentAd->setDataChanged(true);
								}
							break;
							case 'PriceLocal':
							case 'PriceGlobal':
								if(intval($fields[$key]->getValue()) != $adc->CurrentAd->__call('get'.$objectVar))
								{
									$params[$objectVar] = number_format($fields[$key]->getValue(), 2, '.', '');
									$adc->CurrentAd->setDataChanged(true);
								}
							break;
							//Ad Vehicle
							case 'EuApprovedDate':
							case 'TechApprovedDate':
							case 'YearReg':
							case 'FirstTimeReg':
								if(self::formatDateTime($fields[$key]->getValue(), 'd.m.Y') !== $adc->CurrentAd->__call('get'.$objectVar))
								{
									if(self::formatDateTime($fields[$key]->getValue(), 'd.m.Y') != date('d.m.Y', 0))
									{
										$params[$objectVar] = self::formatDateTime($fields[$key]->getValue(), 'd.m.Y');
										$adc->CurrentAd->setDataChanged(true);
									}
								}
							//Ad Vehicle End
							//Ad Transport
							case 'FromDate':
							case 'ToDate':
							//Ad Transport End
							//Ad Employement
							case 'DateStart':
							case 'DateDue':
							//Ad Employement End
								if(self::formatDateTime($fields[$key]->getValue()) !== $adc->CurrentAd->__call('get'.$objectVar))
								{
									if(self::formatDateTime($fields[$key]->getValue(), 'd.m.Y') != date('d.m.Y', 0))
									{
										$params[$objectVar] = self::formatDateTime($fields[$key]->getValue(), 'd.m.Y');
										$adc->CurrentAd->setDataChanged(true);
									}
									/*
									$params[$objectVar] = self::formatDateTime($fields[$key]->getValue());
									$adc->CurrentAd->setDataChanged(true); */
								}
							break;
							case 'DateActiveStart':
							//Ad Publish Date
								if(self::formatDateTime($fields[$key]->getValue()) !== $adc->CurrentAd->__call('get'.$objectVar))
								{
									if(strtotime(self::formatDateTime($fields[$key]->getValue(), 'd.m.Y')) >= strtotime(date('d.m.Y')))
									{
										if($fields['TimeActiveStart']->getValue() != '')
										{ $time = ' '.$fields['TimeActiveStart']->getValue(); }
										else
										{ $time = ' 00:00:00'; }
										
										$params[$objectVar] = self::formatDateTime($fields[$key]->getValue(), 'Y-m-d').$time;
										$adc->CurrentAd->setDataChanged(true);
									}
								}
							break;
						}
					}
					if(count($params) > 0)
					{ $adc->CurrentAd->setValues($params); }
				}
				if(($_POST['LocationCoords']) && ($_POST['LocationCoords'] != $adc->CurrentAd->getLocationCoords()))
				{
					$adc->CurrentAd->setLocationCoords(self::formatText($_POST['LocationCoords']));
					$adc->CurrentAd->setDataChanged(true);
				}
				//if($adc->CurrentAd->getPartnerStatus() > 1)
				//{ $adc->CurrentAd->setDateModified(date('Y-m-d H:i:s')); }
				$adc->CurrentAd->Update();
				$adc->setTTL(0);
			}
		}
	}
	
	public function editAdImages()
	{
		global $katana;
		global $adc;
		$adc->setTTL(0);
		if($adc->getCurrentAdId() > 0)
		{
			if(is_object($adc->getCurrentAd()))
			{
				if($_FILES['Image'])
				{
					$file = $_FILES['Image'];
					if($file["name"] != '')
					{
						if($file['size'] > 0)
						{ $adc->CurrentAd->uploadImage($_FILES['Image']); }
						else
						{ $error['Image'] = 'image file size exceded 1mb'; }
					}
					$adc->CurrentAd->setItemLoaded('images', false);
				}
				if($_FILES['Images'])
				{
					$fh = new File();
					$files = $fh->reArrayFiles($_FILES['Images']);
					if(is_array($files))
					{
						foreach($files as $file)
						{
							if($file["name"] != '')
							{
								if($file['size'] > 0)
								{ $adc->CurrentAd->uploadImage($file); }
								else
								{ $error['Image'] = 'image file size exceded 1mb'; }
							}
							$adc->CurrentAd->setItemLoaded('images', false);
						}
					}
				}
				
				if(intval($_POST['del_img_id']) > 0)
				{ 
					$adc->CurrentAd->deleteImage(intval($_POST['del_img_id']));
					$adc->CurrentAd->setItemLoaded('images', false);
				}
				if($_POST['up'] > 0)
				{ 
					$adc->setTableItemOrderUp($_POST['up'], 'am_ad_images', 'imageOrder', 'adId');
					$adc->CurrentAd->setImages(array());
					$adc->CurrentAd->setItemLoaded('images', false);
				}
				if($_POST['down'] > 0)
				{ 
					$adc->setTableItemOrderDown($_POST['down'], 'am_ad_images', 'imageOrder', 'adId');
					$adc->CurrentAd->setImages(array());
					$adc->CurrentAd->setItemLoaded('images', false);
				}
				if(intval($_POST['rotate_cw']) > 0)
				{ 
					$adc->CurrentAd->rotateImage(intval($_POST['rotate_cw']), 'cw');
					$adc->CurrentAd->setItemLoaded('images', false);
				}
				if(intval($_POST['rotate_ccw']) > 0)
				{ 
					$adc->CurrentAd->rotateImage(intval($_POST['rotate_ccw']), 'ccw');
					$adc->CurrentAd->setItemLoaded('images', false);
				}
			}
		}
	}
	
	public function editAdFiles()
	{
		global $katana;
		global $adc;
		$adc->setTTL(0);
		if($adc->getCurrentAdId() > 0)
		{
			if(is_object($adc->getCurrentAd()))
			{
				if($_FILES['File'])
				{
					$file = $_FILES['File'];
					if($file["name"] != '')
					{
						if($file['size'] < MAX_FILE_SIZE)
						{ $adc->CurrentAd->uploadFile($_FILES['File']); }
						else
						{ $error['File'] = 'file file too large'; }
					}
					$adc->CurrentAd->setItemLoaded('Files', false);
				}
				if(intval($_POST['del_file_id']) > 0)
				{ 
					$adc->CurrentAd->deleteFile(intval($_POST['del_file_id']));
					$adc->CurrentAd->setItemLoaded('Files', false);
				}
				if($_POST['up_file'] > 0)
				{ 
					$adc->setTableItemOrderUp($_POST['up_file'], 'am_ad_files', 'FileOrder', 'AdId');
					$adc->CurrentAd->setFiles(array());
					$adc->CurrentAd->setItemLoaded('Files', false);
				}
				if($_POST['down_file'] > 0)
				{ 
					$adc->setTableItemOrderDown($_POST['down_file'], 'am_ad_files', 'FileOrder', 'AdId');
					$adc->CurrentAd->setFiles(array());
					$adc->CurrentAd->setItemLoaded('Files', false);
				}
			}
		}
	}
	
	function findAdTypeProductId($ad)
	{
		$productId = 0;
		if(is_object($ad))
		{
			global $adc;
			$type = $adc->getAdType($ad->getTypeId());
			if(is_object($type))
			{
				if($ad->getIsRent())
				{
					if($ad->getIsBuying())
					{  
						if($type->getProductBuyId() > 0)
						{ $productId = $type->getProductBuyId(); }
					}
					else
					{
						if($type->getProductRentId() > 0)
						{ $productId = $type->getProductRentId(); }
					}
				}
				else
				{
					if($ad->getIsBuying())
					{  
						if($type->getProductBuyId() > 0)
						{ $productId = $type->getProductBuyId(); }
					}
					else
					{
						if($type->getProductId() > 0)
						{ $productId = $type->getProductId(); }
					}
				}
			}
		}
		return $productId;
	}
	
	function findAdProductId($ad)
	{
		$productId = 0;
		if(is_object($ad))
		{
			global $adc;
			global $user;
			
			if($adc->getSetting('AdProducts') > 0)
			{
				$productId = self::findAdTypeProductId($ad);
				//#PARTNER#
				//Provjera partner statusa ukoliko je musterija odobren partner
				if(($productId > 0) && ($user->getPartnerStatus() > 1))
				{
					$adc->setUserId($user->getId());
					$adc->Search['AND'] = ' AND ad.productId=0 AND ad.isBuying=0 AND ad.isRent=0 AND ad.typeId<5'; //Search active ads where user has not paid manually and it is payable ad
					//echo '<br />$user->getPartnerStatus():'.$user->getPartnerStatus();
					//echo '<br />$adc->getAdsActiveCount():'.$adc->getAdsActiveCount();
					if($user->getPartnerStatus() > $adc->getAdsActiveCount())
					{ $productId = 0; } //Partner ima dovoljno kredita
					else
					{
						//echo '<br />$_POST[UpgradeCheck]:'.$_POST['UpgradeCheck'];
						if(intval($_POST['UpgradeCheck']) > 0)
						{
							//echo '<br />$_POST[PartnerStatusUpgrade]:'.$_POST['PartnerStatusUpgrade'];
							if(intval($_POST['PartnerStatusUpgrade']) > 0) //Partner zeli nadogradnju
							{ 
								if($adc->getAdsActiveCount() < 15)
								{ 
									if($user->upgradePartnerStatus(15) > 0)
									{ $productId = 0; }
								}
								else
								{ 
									if($user->upgradePartnerStatus(10000) > 0)
									{ $productId = 0; }
								}
							} 
						}
					}
					
					//echo '<br />$productId:'.$productId;
				}
				if(($productId == 0) && ($ad->getGalleryDisplay() > 0))
				{ $productId = 6; }
				$adc->Search['AND'] = '';
				//#PARTNER-END#
			}
		}
		return $productId;
	}
	
	function addAd($newAd)
	{
		$id = 0;
		if(is_object($newAd))
		{ 
			global $adc;
			global $user;
			if(($newAd->getUserId() > 0) && ($newAd->getTypeId() > 0))
			{
				$productId = self::findAdProductId($newAd);
				//$newAd->setProductId($productId);
				
				//$newAd->insert();
				$insert .= '`typeId`';
				$values .= ''.$newAd->getTypeId();
				
				$insert .= ', `catId`';
				$values .= ', '.$newAd->getCatId();
				
				if($newAd->getTitle() != '')
				{
					$insert  = ', `title`';
					$values  = ', "'.$newAd->getTitle().'"';
				}
				if($newAd->getTitleEn() != '')
				{
					$insert .= ', `titleEn`';
					$values .= ', "'.$newAd->getTitleEn().'"';
				}
				
				$insert .= ', `brandId`';
				$values .= ', '.$newAd->getBrandId();
				
				$insert .= ', `userId`';
				$values .= ', '.$newAd->getUserId();
				
				if($productId > 0)
				{
					if(($newAd->getUseCredits() > 0) && ($user->getCreditsLeft() > 0) && ($newAd->getGalleryDisplay() == 0))
					{
						$newAd->setAdQuotas(-1);
						$creditsUsed = 0;
						$creditsUsed = ($user->getCreditsUsed() + 1);
						$user->setCreditsUsed($creditsUsed);
						$user->saveUser();
						$insert .= ', `AdQuotas`';
						$values .= ', -1';
					}
					else
					{
						$insert .= ', `productId`';
						$values .= ', '.$productId;
						
						$insert .= ', `AdQuotas`';
						$values .= ', '.$newAd->getAdQuotas();
					}
				}
				else
				{
					$insert .= ', `datePaid`';
					$values .= ', NOW()';
				}
				
				$insert .= ', `isBuying`';
				$values .= ', '.$newAd->getIsBuying();
				
				$insert .= ', `isRent`';
				$values .= ', '.$newAd->getIsRent();
				
				$insert .= ', `isNew`';
				$values .= ', '.$newAd->getIsNew();
				
				$insert .= ', `GalleryDisplay`';
				$values .= ', '.$newAd->getGalleryDisplay();
				
				if($newAd->getDescription() != '')
				{
					$insert .= ', `description`';
					$values .= ', "'.$newAd->getDescription().'"';
				}
				
				if($newAd->getDescriptionEn() != '')
				{
					$insert .= ', `descriptionEn`';
					$values .= ', "'.$newAd->getDescriptionEn().'"';
				}
				
				
				$insert .= ', `dateCreated`';
				$values .= ', NOW()';
				
				$sql  = 'INSERT INTO '.DB_PERFIX.'am_ads ('.$insert.') '; 
				$sql .= 'VALUES ('.$values.');';
				$result = mysql_query($sql);
				
				$sql = 'SELECT id FROM '.DB_PERFIX.'am_ads WHERE `userId`='.$newAd->getUserId().' AND `active`=0 AND `dateCreated` > "'.date('Y-m-d H:').'00:00" ORDER BY id DESC LIMIT 1;';
				$result = mysql_query($sql);
				
				if(mysql_num_rows($result) > 0)
				{
					while($row = mysql_fetch_array($result))
					{ $newAd->setId($row['id']); }
				}
				$adc->setTTL(0);
			}
		}
		return $newAd;
	}
}
?>